package com.confee.guanglai.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.confee.guanglai.domain.User;
import com.confee.guanglai.service.UserService;

/**
 * 员工Controller.
 * 
 * @author 李忠
 * 
 */
@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	public UserService userService;

	@ModelAttribute
	public User get(@RequestParam(required = false) Long id) {
		if (id != null) {
			return userService.get(id);
		} else {
			return new User();
		}
	}

	@RequestMapping(value = { "list", "" })
	public String list(String value, HttpServletRequest request, HttpServletResponse response, Model model) {

		String pageNo = request.getParameter("pageNo");
		String pageSize = request.getParameter("pageSize");

		Pageable pageRequest = new PageRequest(StringUtils.isBlank(pageNo) ? 0 : Integer.valueOf(pageNo),
				StringUtils.isBlank(pageSize) ? 20 : Integer.valueOf(pageSize),new Sort(Direction.DESC, "id"));
		
		Page<User> page = userService.find(value, pageRequest);
		model.addAttribute("page", page);
		model.addAttribute("value", value);
		return "user/list";
	}

	@RequestMapping(value = "form")
	public String form(User user, Model model) {
		model.addAttribute("user", user);
		return "user/form";
	}

	@RequestMapping(value = "save")
	public String save(User user, String oldLoginName, String newPassword, HttpServletRequest request, Model model,
			RedirectAttributes redirectAttributes) {
		userService.save(user);
		redirectAttributes.addFlashAttribute("message", "保存员工'" + user.getName() + "'成功");
		redirectAttributes.addFlashAttribute("alertClass", "alert-success");
		return "redirect:/user/list?repage";
	}
}
